package com.lhz.project.system.service.base.impl;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lhz.common.constant.DataStatusEnum;
import com.lhz.common.page.BaseQueryParam;
import com.lhz.common.page.NewPageBean;
import com.lhz.framework.security.HolderInfoManager;
import com.lhz.project.system.mapper.base.DictDataMapper;
import com.lhz.project.system.mapper.base.DictTypeMapper;
import com.lhz.project.system.model.entity.base.DictData;
import com.lhz.project.system.model.entity.base.DictType;
import com.lhz.project.system.model.param.base.DictTypeParam;
import com.lhz.project.system.service.base.DictTypeService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author LiHuaZhi
 * @since 2020-06-22 21:56:13
 */
@Service

public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements DictTypeService {
    @Resource
    private DictTypeMapper dictTypeMapper;

    @Resource
    private DictDataMapper dictDataMapper;

    @Override
    public DictType selectByPrimaryKey(Integer id) {
        return dictTypeMapper.selectByPrimaryKey(id);
    }

    @Override
    public Object listDictType(BaseQueryParam param) {
        return NewPageBean.generatePage(() -> dictTypeMapper.listDictType(param), param, DictType.class);
    }

    @Override
    public int insert(DictTypeParam param) {
        String userId = HolderInfoManager.getUserId();
        DictType dictType = new DictType();
        BeanUtils.copyProperties(param, dictType);

        dictType.setStatus(DataStatusEnum.VALID.getCode());
        dictType.setCreateBy(userId);
        dictType.setUpdateBy(userId);
        return dictTypeMapper.insert(dictType);
    }

    @Override
    public int updateByPrimaryKey(DictTypeParam param) {
        String userId = HolderInfoManager.getUserId();
        DictType dictType = new DictType();
        BeanUtils.copyProperties(param, dictType);

        dictType.setUpdateBy(userId);
        return dictTypeMapper.updateById(dictType);
    }

    @Override
    public int deleteRealByPrimaryKey(Integer id) {
        //查询类型下是否存在数据
        DictType dictType = dictTypeMapper.selectByPrimaryKey(id);
        //根据类型查询
        List<DictData> dictData = dictDataMapper.selectDictDataByType(dictType.getDictType());

        Assert.isTrue(dictData.isEmpty(), "存在字典数据,无法删除!");

        return dictTypeMapper.deleteById(id);
    }

    @Override
    public int deleteRealByPrimaryKeys(List<Integer> ids) {
        return dictTypeMapper.deleteBatchIds(ids);
    }
}